<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use app\common\library\Token;
use app\common\model\Category as CategoryModel;
use app\admin\model\pet\Adopts as AdoptsModel;

class Adopts extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = 'pet';

    protected $model = null;

    public function _initialize(){
        parent::_initialize();
        $this->model = new AdoptsModel();
    }

    public function index()
    {
        $category = CategoryModel::getCategoryArray(null,'normal');
        $catIds = $dogIds = $otherIds =[];
        
        foreach ($category as $key => $value) {
            if($value['type'] == 'cat'){
                $catIds[] = $value['id']; 
                $cats = $this->model
                        ->with('category') 
                        ->field(['id','cover','address','createtime','age','category'])    
                        ->order('weight','aesc')
                        ->limit(8)
                        ->where(['status'=>'normal'])
                        ->where(['category'=>['in',$catIds]])
                        ->select();
            }
            if($value['type'] == 'dog'){
                $dogIds[] = $value['id']; 
                $dogs = $this->model
                        ->with('category') 
                        ->field(['id','cover','address','createtime','age','category'])    
                        ->order('weight','aesc')
                        ->limit(4)
                        ->where(['status'=>'normal'])
                        ->where(['category'=>['in',$dogIds]])
                        ->select();
            }
            if($value['type'] == 'other'){
                $otherIds[] = $value['id']; 
                $others = $this->model
                        ->with('category') 
                        ->field(['id','cover','address','createtime','age','category'])    
                        ->order('weight','aesc')
                        ->where(['status'=>'normal'])
                        ->where(['category'=>['in',$otherIds]])
                        ->select();
            }
        }
        //halt(collection($cats)->toArray());
        $data = [
            'cat'   =>  collection($cats)->toArray(),
            'dog'   =>  collection($dogs)->toArray(),
            'other'   =>  collection($others)->toArray(),
        ]; 
        
        return $this->view->fetch('',[
            'title' =>  '我要领养',
            'data'  =>  $data
        ]);
    }

    public function details($pet_id = null)
    {
        if($pet_id){
            $info = $this->model->where('status','normal')->find($pet_id);
            if(!$info){
                $this->error('抱歉，查无此宠物！');
            }
            return $this->view->fetch('',[
                'title' =>  '宠物详情',
                'data'  =>  $info
            ]);
        }

    }

}
